// 二维码生成/识别工具
class QRCodeTool {
    /**
     * 生成二维码
     * @param {string} text - 要生成二维码的文本
     * @param {Object} options - 生成选项
     * @returns {Promise<Object>} - 处理结果
     */
    static async generate(text, options = {}) {
        try {
            if (!text || text.trim() === '') {
                return { success: false, error: '请输入要生成二维码的内容' };
            }

            const {
                width = 256,
                height = 256,
                margin = 4,
                color = {
                    dark: '#000000',
                    light: '#FFFFFF'
                },
                errorCorrectionLevel = 'M'
            } = options;

            // 使用在线API生成二维码（临时方案）
            const canvas = document.createElement('canvas');
            const ctx = canvas.getContext('2d');
            canvas.width = width;
            canvas.height = height;
            
            // 创建一个临时的图片来显示二维码
            const img = new Image();
            img.crossOrigin = 'anonymous';
            
            return new Promise((resolve) => {
                img.onload = () => {
                    // 填充背景
                    ctx.fillStyle = color.light;
                    ctx.fillRect(0, 0, width, height);
                    
                    // 计算二维码在canvas中的位置
                    const qrSize = width - 2 * margin;
                    const x = margin;
                    const y = margin;
                    
                    // 绘制二维码图片
                    ctx.drawImage(img, x, y, qrSize, qrSize);
                    
                    resolve({
                        success: true,
                        data: {
                            canvas: canvas,
                            dataURL: canvas.toDataURL('image/png'),
                            text: text,
                            size: `${width}x${width}`,
                            errorCorrectionLevel,
                            margin
                        }
                    });
                };
                
                img.onerror = () => {
                    resolve({ success: false, error: '二维码生成失败，请检查网络连接' });
                };
                
                // 使用qr-server.com的API（免费且可靠）
                const encodedText = encodeURIComponent(text);
                const qrUrl = `https://api.qrserver.com/v1/create-qr-code/?size=${width-2*margin}x${width-2*margin}&data=${encodedText}&bgcolor=${color.light.replace('#', '')}&color=${color.dark.replace('#', '')}&margin=${margin}`;
                img.src = qrUrl;
            });
        } catch (error) {
            return { success: false, error: '生成二维码失败: ' + error.message };
        }
    }

    /**
     * 识别二维码
     * @param {File|HTMLImageElement|HTMLCanvasElement|string} input - 图片文件、图片元素、canvas或base64数据
     * @returns {Promise<Object>} - 处理结果
     */
    static async decode(input) {
        try {
            // 检查jsQR库是否可用
            if (typeof jsQR === 'undefined') {
                return { success: false, error: '二维码识别库未加载，请刷新页面重试' };
            }

            let canvas, ctx;

            if (input instanceof File) {
                // 处理文件
                const result = await this._processFile(input);
                if (!result.success) {
                    return result;
                }
                canvas = result.canvas;
                ctx = result.ctx;
            } else if (input instanceof HTMLImageElement) {
                // 处理图片元素
                const result = this._processImage(input);
                canvas = result.canvas;
                ctx = result.ctx;
            } else if (input instanceof HTMLCanvasElement) {
                // 处理canvas
                canvas = input;
                ctx = canvas.getContext('2d');
            } else if (typeof input === 'string') {
                // 处理base64数据
                const result = await this._processBase64(input);
                if (!result.success) {
                    return result;
                }
                canvas = result.canvas;
                ctx = result.ctx;
            } else {
                return { success: false, error: '不支持的输入类型' };
            }

            // 获取图像数据
            const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
            
            // 识别二维码
            const qrCode = jsQR(imageData.data, imageData.width, imageData.height, {
                inversionAttempts: "dontInvert",
            });

            if (qrCode) {
                return {
                    success: true,
                    data: {
                        text: qrCode.data,
                        location: qrCode.location,
                        imageSize: {
                            width: canvas.width,
                            height: canvas.height
                        },
                        corners: qrCode.location ? [
                            qrCode.location.topLeftCorner,
                            qrCode.location.topRightCorner,
                            qrCode.location.bottomLeftCorner,
                            qrCode.location.bottomRightCorner
                        ] : null
                    }
                };
            } else {
                return { success: false, error: '未识别到二维码，请确保图片清晰且包含有效的二维码' };
            }
        } catch (error) {
            return { success: false, error: '识别二维码失败: ' + error.message };
        }
    }

    /**
     * 处理文件
     * @private
     */
    static async _processFile(file) {
        return new Promise((resolve) => {
            // 检查文件类型
            if (!file.type.startsWith('image/')) {
                resolve({ success: false, error: '请选择图片文件' });
                return;
            }

            // 检查文件大小 (限制为10MB)
            const maxSize = 10 * 1024 * 1024;
            if (file.size > maxSize) {
                resolve({ success: false, error: '图片文件太大，请选择小于10MB的图片' });
                return;
            }

            const reader = new FileReader();
            reader.onload = (e) => {
                const img = new Image();
                img.onload = () => {
                    const result = this._processImage(img);
                    resolve({ success: true, ...result });
                };
                img.onerror = () => {
                    resolve({ success: false, error: '图片加载失败' });
                };
                img.src = e.target.result;
            };
            reader.onerror = () => {
                resolve({ success: false, error: '文件读取失败' });
            };
            reader.readAsDataURL(file);
        });
    }

    /**
     * 处理图片元素
     * @private
     */
    static _processImage(img) {
        const canvas = document.createElement('canvas');
        const ctx = canvas.getContext('2d');
        
        canvas.width = img.width || img.naturalWidth;
        canvas.height = img.height || img.naturalHeight;
        
        ctx.drawImage(img, 0, 0);
        
        return { canvas, ctx };
    }

    /**
     * 处理base64数据
     * @private
     */
    static async _processBase64(base64Data) {
        return new Promise((resolve) => {
            const img = new Image();
            img.onload = () => {
                const result = this._processImage(img);
                resolve({ success: true, ...result });
            };
            img.onerror = () => {
                resolve({ success: false, error: 'Base64图片数据无效' });
            };
            
            // 如果不包含data URI前缀，添加它
            if (!base64Data.startsWith('data:')) {
                base64Data = 'data:image/png;base64,' + base64Data;
            }
            
            img.src = base64Data;
        });
    }

    /**
     * 验证输入是否为有效的二维码内容
     * @param {string} text - 要验证的文本
     * @returns {Object} - 验证结果
     */
    static validateContent(text) {
        try {
            if (!text || text.trim() === '') {
                return { success: false, error: '内容不能为空' };
            }

            // 检查长度限制 (根据纠错等级和版本，一般限制在几千字符)
            const maxLength = 3000;
            if (text.length > maxLength) {
                return { success: false, error: `内容过长，最多支持${maxLength}个字符` };
            }

            // 检测内容类型
            let contentType = 'text';
            if (/^https?:\/\//.test(text)) {
                contentType = 'url';
            } else if (/^mailto:/.test(text)) {
                contentType = 'email';
            } else if (/^tel:/.test(text)) {
                contentType = 'phone';
            } else if (/^wifi:/.test(text)) {
                contentType = 'wifi';
            }

            return {
                success: true,
                data: {
                    contentType,
                    length: text.length,
                    estimatedSize: this._estimateQRSize(text.length),
                    canOptimize: text.length > 100
                }
            };
        } catch (error) {
            return { success: false, error: '内容验证失败: ' + error.message };
        }
    }

    /**
     * 估算二维码大小
     * @private
     */
    static _estimateQRSize(textLength) {
        if (textLength <= 25) return '21x21 (版本1)';
        if (textLength <= 47) return '25x25 (版本2)';
        if (textLength <= 77) return '29x29 (版本3)';
        if (textLength <= 114) return '33x33 (版本4)';
        if (textLength <= 154) return '37x37 (版本5)';
        if (textLength <= 195) return '41x41 (版本6)';
        return '45x45+ (版本7+)';
    }

    /**
     * 获取常用二维码模板
     */
    static getTemplates() {
        return {
            url: {
                name: 'URL链接',
                template: 'https://example.com',
                description: '生成网站链接二维码'
            },
            email: {
                name: '邮箱地址',
                template: 'mailto:example@email.com?subject=主题&body=内容',
                description: '生成邮件二维码'
            },
            phone: {
                name: '电话号码',
                template: 'tel:+86-138-0000-0000',
                description: '生成电话二维码'
            },
            sms: {
                name: '短信',
                template: 'sms:+86-138-0000-0000?body=短信内容',
                description: '生成短信二维码'
            },
            wifi: {
                name: 'WiFi信息',
                template: 'WIFI:T:WPA;S:网络名称;P:密码;H:false;;',
                description: '生成WiFi连接二维码'
            },
            vcard: {
                name: '联系人信息',
                template: 'BEGIN:VCARD\nVERSION:3.0\nFN:姓名\nORG:公司\nTEL:+86-138-0000-0000\nEMAIL:example@email.com\nEND:VCARD',
                description: '生成联系人二维码'
            },
            location: {
                name: '地理位置',
                template: 'geo:39.9042,116.4074?q=天安门广场',
                description: '生成地理位置二维码'
            }
        };
    }

    /**
     * 获取纠错等级选项
     */
    static getErrorCorrectionLevels() {
        return {
            'L': { name: '低 (7%)', description: '适用于干净环境' },
            'M': { name: '中 (15%)', description: '推荐设置' },
            'Q': { name: '较高 (25%)', description: '适用于复杂环境' },
            'H': { name: '高 (30%)', description: '适用于恶劣环境' }
        };
    }
}